import axios, { AxiosInstance, AxiosError, AxiosResponse } from "axios";
import { message } from "antd";
import { ResultData } from "@/api/interface";

class RequestHttp {
	service: AxiosInstance;
	public constructor() {
		// 实例化axios
		this.service = axios.create({
			// 默认地址请求地址，可在 .env 开头文件中修改
			baseURL: import.meta.env.VITE_API_URL as string,
			// 设置超时时间（10s）
			timeout: 10000
		});

		/**
		 * @description 请求拦截器
		 */
		this.service.interceptors.request.use(
			(config: any) => {
				return {
					...config,
					headers: { ...config.headers, token: "1233" }
				};
			},
			(error: AxiosError) => {
				return Promise.reject(error);
			}
		);

		/**
		 * @description 响应拦截器
		 */
		this.service.interceptors.response.use(
			(response: AxiosResponse) => {
				const res = response.data;
				if (res.code === 200) {
					return Promise.resolve(res);
				} else {
					message.error(res.msg);
					return Promise.reject(res);
				}
			},
			async (error: AxiosError) => {
				const { response } = error;
				// 请求超时单独判断，请求超时没有 response
				if (error.message.indexOf("timeout") !== -1) message.error("请求超时，请稍后再试");
				// 根据响应的错误状态码，做不同的处理
				if (response) checkStatus(response.status);
				return Promise.reject(error);
			}
		);
	}

	// * 常用请求方法封装
	get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.get(url, { params, ..._object });
	}
	post<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.post(url, params, _object);
	}
	put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.put(url, params, _object);
	}
	delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
		return this.service.delete(url, { params, ..._object });
	}
}

/**
 * @description: 校验网络请求状态码
 * @param {Number} status
 * @return void
 */
export const checkStatus = (status: number): void => {
	switch (status) {
		case 400:
			message.error("请求失败！请您稍后重试");
			break;
		case 401:
			message.error("登录失效！请您重新登录");
			break;
		case 403:
			message.error("当前账号无权限访问！");
			break;
		case 404:
			message.error("你所访问的资源不存在！");
			break;
		case 405:
			message.error("请求方式错误！请您稍后重试");
			break;
		case 408:
			message.error("请求超时！请您稍后重试");
			break;
		case 500:
			message.error("服务异常！");
			break;
		case 502:
			message.error("网关错误！");
			break;
		case 503:
			message.error("服务不可用！");
			break;
		case 504:
			message.error("网关超时！");
			break;
		default:
			message.error("请求失败！");
	}
};

export default new RequestHttp();
